package com.digitalchina.lxnsy.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.digitalchina.lxnsy.toolkit.ToastUtil;

import java.util.List;

/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bigdata.base
 * 创建人：郑皓
 * 创建时间：2016/5/23 16:32
 * 修改备注：
 * ================================================
 */


public abstract class BaseAdapter<H, T> extends android.widget.BaseAdapter {

    protected Context context;

    protected List<T> listData;

    protected LayoutInflater layoutInflater;

    public BaseAdapter(Context context, List<T> listData) {
        this.context = context;
        this.listData = listData;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return listData == null ? 0 : listData.size();
    }

    @Override
    public Object getItem(int position) {
        return listData == null ? null : listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public List<T> getListData() {
        return listData;
    }

    public void setListData(List<T> listData) {
        this.listData = listData;
        notifyDataSetChanged();
    }

    public void clearListData() {
        this.listData.clear();
        notifyDataSetChanged();
    }

    public void appendToList(List<T> list) {
        if (list == null)
            return;

        this.listData.addAll(list);
        notifyDataSetChanged();
    }


    public View inflate(int layoutId, ViewGroup parent) {
        return layoutInflater.inflate(layoutId, parent, false);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        H holder = null;
        if (convertView == null) {
            convertView = buildConvertView(layoutInflater, parent);
            holder = buildHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (H) convertView.getTag();
        }
        bindViewData(holder, listData.get(position), position);

        return convertView;
    }

    /**
     * 建立convertView
     *
     * @param layoutInflater
     */
    public abstract View buildConvertView(LayoutInflater layoutInflater, ViewGroup parent);

    /**
     * 建立视图Holder
     *
     * @param convertView
     */
    public abstract H buildHolder(View convertView);

    /**
     * 绑定数据
     *
     * @param holder
     * @param t
     * @param position
     */
    public abstract void bindViewData(H holder, T t, int position);

    /**
     * 提示语
     *
     * @param strMsg
     */
    protected void showToast(String strMsg) {
        ToastUtil.showToast(context, strMsg);
    }


}
